package cn.wind.xboot.core.utils;

import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import java.util.Set;

/**
 * <p>Title: ValidationUtil</p>
 * <p>Description: TODO</p>
 *
 * @author xukk
 * @version 1.0
 * @date 2018/6/14
 */
public class ValidationUtil {

    /**
     * 使用hibernate的注解来进行验证
     *
     */
    private static Validator validator = Validation
            .byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();

    /**
     * 功能描述: <br>
     * 〈注解验证参数〉
     *
     * @param obj
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static <T> void validate(T obj,Class... var2) {
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj,var2);
        // 抛出检验异常
        if (constraintViolations.size() > 0) {
            ConstraintViolation c=constraintViolations.iterator().next();
            throw new ValidationException(String.format("参数校验失败: {%s} %s",c.getPropertyPath(),c.getMessage()));
        }
    }
}
